package com.zzz.offer.mergelist;

class ListNode {
    int val;
    ListNode next = null;

    public ListNode(int val) {
        this.val = val;
    }
}

public class MergeList {
    public ListNode Merge(ListNode list1, ListNode list2) {

        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        }

        ListNode newNode;
        if (list1.val > list2.val) {
            newNode = list2;
            list2 = list2.next;
        } else {
            newNode = list1;
            list1 = list1.next;
        }

        ListNode pre = newNode;

        while (list1 != null && list2 != null) {

            if (list1.val > list2.val) {
                pre.next = list2;
                list2 = list2.next;
            } else {
                pre.next = list1;
                list1 = list1.next;
            }
            pre = pre.next;
        }

        if (list1 == null) {
            pre.next = list2;
        }

        if (list2 == null) {
            pre.next = list1;
        }
        return newNode;
    }
}
